package com.ccrfid.rmc6.lbservice3.manager;

import com.ccrfid.rmc6.lbservice3.mq.MqDevStatus;
import com.ccrfid.rmc6.pojo.Constants;
import com.ccrfid.rmc6.service.amq.MqMsgProducer;
import com.ccrfid.rmc6.service.device.LocatorService;
import com.ccrfid.rmc6.service.device.NetreaderService;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class DevStatusManager {
    private static final Logger logger = LoggerFactory.getLogger(DevStatusManager.class);
    private static final String queryStatusTopic = "ccms_query_status";

    @Autowired
    private EventBus eventBus;
    @Autowired
    private MqMsgProducer mqMsgProducer;
    @Autowired
    private LocatorService locatorService;
    @Autowired
    private NetreaderService netreaderService;

    @PostConstruct
    private void init() {
        eventBus.register(this);
    }

    @Scheduled(fixedRate = 2 * 3600 * 1000)
    private void queryStatus() {
        mqMsgProducer.send2Topic(queryStatusTopic, "query devices status");
    }

    @Subscribe
    private void onMqDevStatus(MqDevStatus mqDevStatus) {
        if (mqDevStatus.isLocator()) {
            if (mqDevStatus.isOnline()) {
                locatorService.updateOnlineStatus(mqDevStatus.getId(), Constants.ONLINE_STATUS.ONLINE.id);
                logger.debug("set locator {} online.", mqDevStatus.getId());
            } else {
                locatorService.updateOnlineStatus(mqDevStatus.getId(), Constants.ONLINE_STATUS.OFFLINE.id);
                logger.debug("set locator {} offline.", mqDevStatus.getId());
            }
        } else if (mqDevStatus.isReader()) {
            if (mqDevStatus.isOnline()) {
                netreaderService.updateOnlineStatus(mqDevStatus.getId(), Constants.ONLINE_STATUS.ONLINE.id);
                logger.debug("set net reader {} online.", mqDevStatus.getId());
            } else {
                netreaderService.updateOnlineStatus(mqDevStatus.getId(), Constants.ONLINE_STATUS.OFFLINE.id);
                logger.debug("set net reader {} offline.", mqDevStatus.getId());
            }
        }
    }
}
